package sg.edu.nus.iss.jass.gui;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DebugGraphics;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.BevelBorder;
import sg.edu.nus.iss.jass.exception.ValidationException;
import sg.edu.nus.iss.jass.constant.ActionBtnContants;
import sg.edu.nus.iss.jass.constant.CommonConstants;
import sg.edu.nus.iss.jass.constant.ErrorConstants;
import sg.edu.nus.iss.jass.controller.JobAdvertisementController;
import sg.edu.nus.iss.jass.controller.MainController;
import sg.edu.nus.iss.jass.dto.Company;
import sg.edu.nus.iss.jass.dto.GeographicalLocation;
import sg.edu.nus.iss.jass.dto.JobAdvert;
import sg.edu.nus.iss.jass.dto.Skill;
import sg.edu.nus.iss.jass.dto.SkillReference;
import sg.edu.nus.iss.jass.gui.component.ValidateJTextField;
import sg.edu.nus.iss.jass.util.Util;
import sg.edu.nus.iss.jass.validation.ValidationRule;
/**
 * 
 * @author Tan Pic Cheng
 *
 */
public class JobAdvertisementModifyFormPanel extends FormPanel {
	
	private static final long serialVersionUID = 1L;
	private JobAdvertisementController jobAdvertisementController;
	private MainFrame mainframe;
	private JobAdvert jobAdvert = null;
	
	private List<Skill> skillList;
	private List<SkillReference> skillsList = null;
	private List<GeographicalLocation> locations = null;
	private List<Company> companies = null;
	
	private JLabel createdDateLbl;
	private JLabel displayCreatedDateLbl;
	private JLabel jobTitleLbl; 
	private JLabel jobPositionLbl;
	private JLabel jobDescriptionLbl;
	private JLabel locationCountryLbl;
	private JLabel companyLbl;
	private JLabel startDateLbl;
	private JLabel salaryLbl;
	private JLabel hideSalaryLbl;
	
	private ValidateJTextField jobTitleTxtField; 
	private ValidateJTextField positionTxtField;
	private ValidateJTextField startDateTxtField;
	private ValidateJTextField skillExpTxtField[];
	
	private JTextArea descriptionTxtArea;
	private	JComboBox skillListCbx[];
	private JComboBox skillLevelCbx[]; 	
	private JComboBox countryCbx;
	private JComboBox salaryCbx;
	private JComboBox hideSalaryCbx;
	private JComboBox companyCbx;
	
    private final int NO_OF_SKILLS_ROWS = 5;
	
	String skills[] = {"JAVA", ".NET", "TIBCO"};
	String skillRefIds[] = null;	
	
	String skillLevels[] = {"Select","Beginner", "Intermediate", "Advanced"};
	
	public JobAdvertisementModifyFormPanel(MainFrame mainframe,
			DefaultActionPanel actionPanel, HeaderPanel headerPanel,
			List<SkillReference> skillsList, List<GeographicalLocation> locations,
			List<Company> companies, JobAdvert jobAdvert) {
		// TODO Auto-generated constructor stub
		super(mainframe, actionPanel, headerPanel);
		this.mainframe = mainframe;
		this.jobAdvert = jobAdvert;
		this.skillsList = skillsList;
		this.locations = locations;
		this.companies = companies;
				
		if(jobAdvert != null){
			initGUI();
			setInitData();			
		}
		else{
			clearMsg();
			showMsg(ErrorConstants.ERROR_NO_DATA, false);        	
		}
	}
	private void initGUI() {
        try {
        	setPreferredSize(new Dimension(800, 1550));
        	this.setLayout(null);
        	this.setDebugGraphicsOptions(DebugGraphics.BUFFERED_OPTION);
        	this.setFont(new java.awt.Font("Arial",0,12));
            {
            	createdDateLbl = new JLabel("Created Date:");
            	{
                	createdDateLbl = new JLabel("Created Date:");
                	createdDateLbl.setBounds(22, 29, 91, 21);
                	this.add(createdDateLbl);
                }
                {	
                	displayCreatedDateLbl = new JLabel();                
                	displayCreatedDateLbl.setBounds(159, 29, 150, 21);
                	this.add(displayCreatedDateLbl);
                }
                {
                	jobTitleLbl = new JLabel("Job Title:");
                	jobTitleLbl.setBounds(22, 75, 150, 21);
                	this.add(jobTitleLbl);
                }
                {
                	jobTitleTxtField = new ValidateJTextField("Job Title", ValidationRule.NOT_NULL);
                	jobTitleTxtField.setBounds(159, 73, 150, 25);
                	jobTitleTxtField.setColumns(10);
                	this.add(jobTitleTxtField);
                }
                {			
                	jobPositionLbl = new JLabel("Job Position:");
                	jobPositionLbl.setBounds(20, 123, 148, 21);
                	this.add(jobPositionLbl);
                }
                {			
                	positionTxtField = new ValidateJTextField("Job Title", ValidationRule.NOT_NULL);
                	positionTxtField.setBounds(159, 121, 150, 25);
                	positionTxtField.setColumns(10);
                	this.add(positionTxtField);
                }
                {			
                	jobDescriptionLbl = new JLabel("Job Description:");
                	this.add(jobDescriptionLbl);
                	jobDescriptionLbl.setBounds(19, 173, 150, 21);
                }
                {			
                	descriptionTxtArea = new JTextArea();
                	descriptionTxtArea.setBounds(159, 173, 150, 139);
                	descriptionTxtArea.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
                	descriptionTxtArea.setLineWrap(true);
                	descriptionTxtArea.setWrapStyleWord(true);
                	//descriptionTxtArea.setWrapStyleWord(true);
                	this.add(descriptionTxtArea);
                }     	
                {	skills = getSkillReferenceArray();
                	JPanel skillsPanel = createSkillsPanel();
                	setSkillsData();
	             	skillsPanel.setBounds(22, 330, 650, 300);
	        		this.add(skillsPanel);	        		
                }        		
	            {			
	            	locationCountryLbl = new JLabel("Location Country:");
	            	locationCountryLbl.setBounds(361, 173, 150, 21);
	            	this.add(locationCountryLbl);
	            }
	            {	List<GeographicalLocation> list = locations;
	            	int size = list.size();           

	            	String[] locationList = new String[size];
	            	int i = 0;

	            	String name = null;

	            	for(GeographicalLocation g: list){
	            		name = g.getCountry();
	            		locationList[i] = name;
	            		i++;
	            }            
	            	countryCbx = new JComboBox();
	            	countryCbx.setModel(new DefaultComboBoxModel(locationList));
	            	countryCbx.setBounds(557, 171, 150, 25);
	            	this.add(countryCbx);
	            }
	            {			
	            	companyLbl = new JLabel("Company Name:");
	            	companyLbl.setBounds(361, 220, 150, 21);
	            	this.add(companyLbl);
	            }
	            {	List<Company> list = companies;
	            	int size = list.size();           

	            	String[] companyList = new String[size];
	            	int i = 0;

	            	String name = null;

	            	for(Company c: list){
	            		name = c.getName();
	            		companyList[i] = name;
	            		i++;
	            	}            
	            	companyCbx = new JComboBox();
	            	companyCbx.setModel(new DefaultComboBoxModel(companyList));
	            	companyCbx.setBounds(557, 218, 150, 25);
	            	this.add(companyCbx);
	            }               
	            {			
	            	startDateLbl = new JLabel("Start Date:");
	            	startDateLbl.setBounds(361, 32, 150, 21);
	            	this.add(startDateLbl);
	            }
	            {			
	            	startDateTxtField = new ValidateJTextField("Job Title", ValidationRule.NOT_NULL);
	            	startDateTxtField.setBounds(557, 29, 150, 25);
	            	startDateTxtField.setColumns(10);
	            	this.add(startDateTxtField);
	            }
	            {
	            	salaryLbl = new JLabel("Salary:");
	            	salaryLbl.setBounds(361, 77, 150, 21);
	            	this.add(salaryLbl);
	            }
	            {	salaryCbx = new JComboBox();
            		salaryCbx.setModel(new DefaultComboBoxModel(CommonConstants.salaryRanges.toArray(new String[0])));
	            	salaryCbx.setBounds(557, 73, 150, 25);
	            	this.add(salaryCbx);}
	            }       
            	{	
            		hideSalaryLbl = new JLabel("Hide Salary:");
            		hideSalaryLbl.setBounds(361, 123, 150, 21);
            		this.add(hideSalaryLbl);
            	}
            	{
            		hideSalaryCbx = new JComboBox();
            		hideSalaryCbx.setModel(new DefaultComboBoxModel(new String[] {"Yes", "No"}));
            		hideSalaryCbx.setBounds(557, 121, 150, 25);
            		this.add(hideSalaryCbx);
            	}
            }catch(Exception e) {
            	e.printStackTrace();
         }    
	}
	
private void setInitData(){
	
	displayCreatedDateLbl.setText(Util.getStringFromdate(jobAdvert.getCreation()));
	jobTitleTxtField.setText(jobAdvert.getTitle());
	positionTxtField.setText(jobAdvert.getPosition());
	startDateTxtField.setText(Util.getStringFromdate(jobAdvert.getStartDate()));
	descriptionTxtArea.setText(jobAdvert.getDescription());

	boolean hideSalaryOption = jobAdvert.getIsHideSalary();
	hideSalaryOption = jobAdvert.getIsHideSalary();
	
	if(hideSalaryOption)
	hideSalaryCbx.setSelectedIndex(0);
	else
	hideSalaryCbx.setSelectedIndex(1);

	int min = (int) jobAdvert.getMinSalary();
	int max = (int) jobAdvert.getMaxSalary();
	
	String minSalary = Integer.toString(min);
	String maxSalary = Integer.toString(max);

	StringBuffer sb = new StringBuffer();
	sb.append(minSalary).append("-").append(maxSalary);
	String salaryRange = sb.toString(); 			
	salaryCbx.setSelectedItem(salaryRange);   
	
	String companyName = jobAdvert.getCompany().getName();
	companyCbx.setSelectedItem(companyName);
	
	String country = jobAdvert.getGeographicalLocation().getCountry();
	countryCbx.setSelectedItem(country);
}
private JPanel createSkillsPanel() {
		
		JPanel pane = new JPanel(new GridLayout ());
		
		pane.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.weightx = 1.5;
		c.weighty = 0.5;
		c.insets = new Insets(5, 5, 5, 5);
		c.ipady = 10;
		
		
	    c.gridx = 0;
		c.gridy = 0;
		pane.add(new JLabel("Skill"), c);
		
		c.gridx = 1;
		c.gridy = 0;
		pane.add(new JLabel("Skill Level"), c);

		c.gridx = 2;
		c.gridy = 0;
		pane.add(new JLabel("Years Of Experience"), c);        
		
		skillListCbx = new JComboBox[NO_OF_SKILLS_ROWS];
		int y = 1;
		
		for (int i = 0;i<NO_OF_SKILLS_ROWS;i++) {
			skillListCbx[i] = new JComboBox (skills);
			c.gridx = 0;
			c.gridy = y++;
			pane.add(skillListCbx[i], c);
		}
		
		skillLevelCbx = new JComboBox[NO_OF_SKILLS_ROWS];
		y = 1;
		for (int i = 0;i<NO_OF_SKILLS_ROWS;i++) {
			skillLevelCbx[i] = new JComboBox (skillLevels);
			c.gridx = 1;
			c.gridy = y++;
			pane.add(skillLevelCbx[i], c);
		}

		skillExpTxtField = new ValidateJTextField[NO_OF_SKILLS_ROWS];
		y = 1;
		for (int i = 0;i<NO_OF_SKILLS_ROWS;i++) {
			skillExpTxtField[i] = new ValidateJTextField ("Years Of Experience",ValidationRule.NUMERIC);
			c.ipady = 10;
			c.gridx = 2;
			c.gridy = y++;
			pane.add(skillExpTxtField[i], c);
		}		
		return pane;
}
private String[] getSkillReferenceArray(){
	
	
	if(skillsList != null && skillsList.size() > 0){
		skills = new String[skillsList.size() + 1];
		skillRefIds = new String[skillsList.size() + 1];
		int i = 0;
		
		skills[i] = "Select";
		skillRefIds[i] = "";
		i++;
		Iterator<SkillReference> it = skillsList.iterator();
		
		while(it.hasNext()){
			SkillReference skillref = (SkillReference)it.next();
			skills[i] = skillref.getName();
			skillRefIds[i] = skillref.getId();
			i++;
		}
	}
	
	return skills;
}	
private void setSkillsData(){
	
		skillList = jobAdvert.getSkills();
		
		String skillName = null;
		int skillLvl = 0;
		String skillYrs = null;	
		
		int i = 0;
		
		if(skillList != null && skillList.size() > 0){		

			for(Skill s : skillList){					
				skillName = s.getSkillRef().getName().toString();
				skillLvl = s.getLvl();
				skillYrs = Integer.toString(s.getYearOfExp());

				skillListCbx[i].setSelectedItem(skillName);
				skillLevelCbx[i].setSelectedIndex(skillLvl);
				skillExpTxtField[i].setText(skillYrs);					
				i++;
			}
		}		
		return;
}
@Override
public void actionPerformed(ActionEvent e) {
	// TODO Auto-generated method stub	
	if(e.getActionCommand().equals("Update")){
		submit();
	} else if (e.getActionCommand().equals(ActionBtnContants.CANCEL)) {
		MainController.getInstance().getJobSearchController().startSearchJob();
	}		
	return;		
}
private void reset() {
	// TODO Auto-generated method stub
	jobTitleTxtField.setText(""); 
	positionTxtField.setText("");
	startDateTxtField.setText("");					
	descriptionTxtArea.setText("");	
	countryCbx.setSelectedIndex(0);
	salaryCbx.setSelectedIndex(0);
	hideSalaryCbx.setSelectedIndex(0);
	companyCbx.setSelectedIndex(0);
	//System.out.println(skillExpTxtField.length + "\n" + skillLevelCbx.length);
			
	for(int i = 0; i < skillExpTxtField.length; i++){
		if(!skillExpTxtField [i].getText().isEmpty())
			skillExpTxtField [i].setText("");
			skillListCbx[i].setSelectedIndex(0);
			skillLevelCbx[i].setSelectedIndex(0);
	}		
}
private void submit() {
	// TODO Auto-generated method stub
	displayConfirmationMsg();		
}
private void displayConfirmationMsg() {
	// TODO Auto-generated method stub
	//default icon, custom title
	if (showConfirmDialog("Job Advert", "Update") == 1) {
		// do nothing as it is cancelled
	} else {
		super.clearMsg();
		confirm();
	}		
}
public void errorMsg(){
	clearMsg();
	showMsg("Update Job Advert Error!", false);
}
public void displaySuccessfulMsg(){
	showMsg("Update Job Advert Success!", true);
}	
@Override
public void show() {
	// TODO Auto-generated method stub
	addFormPanel();
}
public void confirm(){
	try {
		Date startDate = Util.getDateFromString(startDateTxtField.getValidatedText());
		String description = descriptionTxtArea.getText();
		boolean isHideSalary = getIsHideSalary();
		boolean isWithdrawn = false;		
		String title = jobTitleTxtField.getValidatedText();
		String position = positionTxtField.getValidatedText();
		float minSalary = getMinSalary();
		float maxSalary = getMaxSalary();
		GeographicalLocation geographicalLocation = getJobLocation();
		
		jobAdvert.setStartDate(startDate);
		jobAdvert.setDescription(description);
		jobAdvert.setIsHideSalary(isHideSalary);
		jobAdvert.setIsWithdrawn(isWithdrawn);
		jobAdvert.setTitle(title);
		jobAdvert.setPosition(position);
		jobAdvert.setMinSalary(minSalary);
		jobAdvert.setMaxSalary(maxSalary);
		jobAdvert.setCompany(getCompany());
		jobAdvert.setGeographicalLocation(geographicalLocation);
		if(skillValidate()){		
		jobAdvert.setSkills(skillList);	
		}
		jobAdvertisementController.processModifyJobAd(jobAdvert);
	} catch (ValidationException e) {
		showMsg(e.getMessage(), false);
	}
}
@SuppressWarnings("unused")
private boolean skillValidate() throws ValidationException {
	
	HashMap<String, Skill> exisitingSkills = new HashMap<String, Skill>();
	
	skillList = new ArrayList<Skill>();
	for (int i = 0;i<NO_OF_SKILLS_ROWS;i++) {
		
		Skill skill = null;
		if(skillListCbx[i] != null && skillListCbx[i].getSelectedItem() != null){
			
			String tmpSkillName = skillListCbx[i].getSelectedItem().toString();
			
			System.out.println("tmpSkillName:" + tmpSkillName);
			
			
			if(!tmpSkillName.equals("Select")){
				
				int tmpSkillIndex = skillListCbx[i].getSelectedIndex();
				String tmpSkillRefId = skillRefIds[tmpSkillIndex]; //ADDED Select as first item
				System.out.println("tmpSkillRefId:" + tmpSkillRefId);
				
				String tmpSkillLevel = skillLevelCbx[i].getSelectedItem().toString();
				System.out.println("tmpSkillLevel:" + tmpSkillLevel);
				
				if(tmpSkillLevel.equals("Select")){
					throw new ValidationException("Please Select Skill Level");
				}
				
				String tmpSkillExp =  skillExpTxtField[i].getValidatedText();
				System.out.println("tmpSkillExp:" + tmpSkillExp);
				if(tmpSkillExp.trim().length() == 0){
					throw new ValidationException("Please enter Years Of Experience");
				}
				
				skill = new Skill();
				skill.setSkillRefId(tmpSkillRefId); 
				skill.setLvl(Util.getSkillLevelCode(tmpSkillLevel));
				skill.setYearOfExp(Integer.parseInt(tmpSkillExp));
				
				if(!exisitingSkills.containsKey(tmpSkillName)){
					skillList.add(skill);
					exisitingSkills.put(tmpSkillName, skill);
				}else {
					throw new ValidationException("Duplicate Skills");
				}
				
			}else if(!skillLevelCbx[i].getSelectedItem().equals("Select") || 
						skillExpTxtField[i].getText().trim().length() > 0){
				
				throw new ValidationException("Incomplete Skill Details ");
			}
		}
	}
	if(skillList.isEmpty()) {
		throw new ValidationException(ErrorConstants.ERROR_NO_SKILL_SPECIFIED);
	}
	return true;
	
}

public String getJobTitle() throws ValidationException{
	return jobTitleTxtField.getValidatedText();
}
public String getJobPosition() throws ValidationException{
	return positionTxtField.getValidatedText();
}
public GeographicalLocation getJobLocation(){
	Object country= (String) countryCbx.getSelectedItem();
	
	for(GeographicalLocation g : this.locations){
		if(g.getCountry().equals(country))
			return g;
	}		
	return null;
}
public Company getCompany() throws ValidationException{
	Object name = (String) companyCbx.getSelectedItem();
	
	for(Company c : this.companies){
		if(c.getName().equals(name))
			return c;
	}		
	return null;
}
public void setController(JobAdvertisementController jobAdvertisementController){
	this.jobAdvertisementController = jobAdvertisementController;
	//this.addJobPanel.setJobAdvertisementController(jobAdvertisementController);
}
public boolean getIsHideSalary(){
	Object st= (String) hideSalaryCbx.getSelectedItem();
	boolean status = ((st.equals("Yes"))? true : false);
	
	return status;		
}
public String[] getSalary(){		
	Object salary = (String)salaryCbx.getSelectedItem();
	String[] sly = ((String) salary).split("-");
	
	return sly;		
}
public float getMinSalary(){		
	String[] array = getSalary();
	float maxSalary = Float.parseFloat(array[0]);
	return maxSalary;		
}
public float getMaxSalary(){		
	String[] array = getSalary();
	float maxSalary = Float.parseFloat(array[1]);
	return maxSalary;		
}
}
